<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索关键字"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="form.serviceType"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in taskConfigStore.serviceTypes"
            :key="item.standardCode"
            :label="item.displayName"
            :value="item.standardCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-select
          v-model="form.country"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in taskConfigStore.allCountryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件类型" prop="type">
        <el-select
          v-model="form.type"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option value="INPUT" label="上传文件" />
          <el-option value="OUTPUT" label="下载文件" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          class="!w-[220px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
        <el-button
          type="danger"
          :disabled="!selectionList.length"
          @click="delFilesBatch"
        >
          批量删除文件
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="fileId" label="文件ID" width="320" />
      <el-table-column prop="fileName" label="文件名称" />
      <el-table-column prop="fileSize" label="文件大小" width="120" />
      <el-table-column prop="taskId" label="任务ID" width="80" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="contentType" label="内容类型" width="120" />
      <el-table-column prop="serviceType" label="服务类型" width="120" />
      <el-table-column prop="country" label="国家" width="100" />
      <el-table-column prop="status" label="状态" width="100" />
      <el-table-column prop="lineCount" label="行数" width="80" />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
        width="160"
      />
      <el-table-column label="操作" fixed="right" width="160">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            :loading="scope.row.loading"
            @click="handleDownload(scope.row.id)"
          >
            下载
          </el-button>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定删除该文件吗？"
            @confirm="confirmStatus(scope.row.id)"
          >
            <template #reference>
              <el-button link type="danger" size="small"> 删除 </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from "vue";
import { handleAutoUTC8 } from "@/utils/tools";
import { ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { InfoFilled } from "@element-plus/icons-vue";
import {
  getFileList,
  downloadFileById,
  deleteFile,
  deleteFilesBatch
} from "@/api/adminFileApi";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import { message } from "@/utils/message";
const taskConfigStore = useTaskConfigHook();
const formRef = ref();
const loading = ref(false);
const form = reactive({
  serviceType: "",
  time: "",
  type: "",
  keyword: "",
  country: "",
  startDate: "",
  endDate: ""
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const selectionList = ref([]);
const delLoading = ref(false);
const handleSelectionChange = (val: any) => {
  selectionList.value = val.map((item: any) => item.id);
};
const delFilesBatch = async () => {
  try {
    await ElMessageBox.confirm("你确定要删除这些文件吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    delLoading.value = true;
    await deleteFilesBatch(selectionList.value);
    message("删除成功", { type: "success" });
    onSearch();
  } finally {
    delLoading.value = false;
  }
};
const handleDownload = async (id: number) => {
  const index = tableData.value.findIndex((item: any) => item.id === id);
  try {
    tableData.value[index].loading = true;
    await downloadFileById(id);
  } catch (error) {
    console.log(error);
  } finally {
    tableData.value[index].loading = false;
  }
};
const tableData = ref([]);

watch(
  () => form.time,
  (newVal, oldVal) => {
    if (newVal) {
      form.startDate = newVal[0];
      form.endDate = newVal[1];
    } else {
      form.startDate = "";
      form.endDate = "";
    }
  }
);

async function onSearch() {
  const { time, ...reset } = form;
  const params = {
    page: pagination.currentPage,
    size: pagination.pageSize,
    ...reset
  };
  const { data } = await getFileList(params);
  const { records, total, size, current } = data;
  tableData.value = records.map((item: any) => {
    return {
      ...item,
      loading: false
    };
  });
  pagination.total = total;
  pagination.pageSize = size;
  pagination.currentPage = current;
}
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  form.startDate = "";
  form.endDate = "";
  pagination.currentPage = 1;
  onSearch();
};
const confirmStatus = async (fileId: number) => {
  try {
    await deleteFile(fileId);
    message("删除成功", { type: "success" });
    onSearch();
  } catch (error) {
    console.log(error);
  }
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
